package com.siwei.eqi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.siwei.eqi.pojo.dto.excel.BatchResultExcelDTO;
import com.siwei.eqi.pojo.entity.DeliveryTaskBatchResult;
import com.siwei.eqi.mapper.DeliveryTaskBatchResultMapper;
import com.siwei.eqi.pojo.vo.BatchResultVO;
import com.siwei.eqi.service.IDeliveryTaskBatchResultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siwei.eqi.util.ObectUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 汇交结果表 服务实现类
 * </p>
 *
 * @author hzl
 * @since 2025-04-02
 */
@Service
public class DeliveryTaskBatchResultServiceImpl extends ServiceImpl<DeliveryTaskBatchResultMapper, DeliveryTaskBatchResult> implements IDeliveryTaskBatchResultService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importFile(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<BatchResultExcelDTO> list = EasyExcel.read(inputStream)
                .head(BatchResultExcelDTO.class)
                // 设置sheet,默认读取第一个
                .sheet("待定")
                // 设置标题所在行数
                .headRowNumber(2)
                .doReadSync();
        List<BatchResultExcelDTO> sleepList = list.stream().filter(sleepDTO -> ObectUtil.checkObjFieldIsNotNull(sleepDTO))
                .collect(Collectors.toList());

        System.out.println(sleepList);
        sleepList.forEach(sleepDTO -> {
            DeliveryTaskBatchResult entity = new DeliveryTaskBatchResult();
            entity.setTitle(sleepDTO.getTitle());
            entity.setProvince(sleepDTO.getProvince());
            entity.setCounty(sleepDTO.getCounty());
            // todo:2023年原始值
            baseMapper.insert(entity);
        });
        return true;
    }

    @Override
    public List<BatchResultVO> queryList(String batchId) {
        List<DeliveryTaskBatchResult> resultList = this.list(new LambdaQueryWrapper<DeliveryTaskBatchResult>()
                .eq(DeliveryTaskBatchResult::getBatchId, batchId));
        if (CollectionUtils.isEmpty(resultList)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultList,BatchResultVO.class);
    }
}
